/**    
* @Title: UserServiceImpl.java  
* @Package com.kaver.sso.service.impl   
* @author roc   
* @date Jul 26, 2021 2:15:14 PM  
* @version V1.0  
* @copyright kaver 
*/
package com.kaver.sso.service.impl;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaver.sso.config.CommonConfig;
import com.kaver.sso.config.Constant;
import com.kaver.sso.dao.po.SsoApp;
import com.kaver.sso.dao.po.SsoDept;
import com.kaver.sso.dao.po.SsoLoginRecord;
import com.kaver.sso.dao.po.SsoUser;
import com.kaver.sso.dao.service.SsoAppDao;
import com.kaver.sso.dao.service.SsoDeptDao;
import com.kaver.sso.dao.service.SsoLoginRecordDao;
import com.kaver.sso.dao.service.SsoUserDao;
import com.kaver.sso.def.BizException;
import com.kaver.sso.def.enums.CodeEnum;
import com.kaver.sso.def.req.AddUserReq;
import com.kaver.sso.def.req.LockUserReq;
import com.kaver.sso.def.req.ResetPwdReq;
import com.kaver.sso.def.req.UpdatePwdReq;
import com.kaver.sso.def.req.UpdateUserReq;
import com.kaver.sso.def.req.UserPageListReq;
import com.kaver.sso.def.resp.PageResp;
import com.kaver.sso.def.resp.User;
import com.kaver.sso.helper.SsoUserHolder;
import com.kaver.sso.service.RoleService;
import com.kaver.sso.service.UserService;
import com.kaver.sso.utils.Base64Utils;
import com.kaver.sso.utils.CR;
import com.kaver.sso.utils.RsaUtil;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;

/**  
* @ClassName: UserServiceImpl  
* @Description: 用户服务
* @author roc  
* @date Jul 26, 2021 2:15:14 PM  
*    
*/
@Slf4j
@Service
public class UserServiceImpl implements UserService{
    @Autowired
    CommonConfig config;
    @Autowired
    SsoUserDao ssoUserDao;
    @Autowired
    SsoLoginRecordDao ssoLoginRecordDao;
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    SsoDeptDao ssoDeptDao;
    @Autowired
    RoleService roleService;
    @Autowired
    SsoAppDao ssoAppDao;
    
    @Override
    public Boolean canLogin(String userAcc) {
        SsoUser ssoUser = ssoUserDao.queryByUserAccount(userAcc);
        if (ssoUser != null) {
           Integer userStatus = ssoUser.getUserStatus();
           if (userStatus == 0) {
               return false;
           } else {
               return true;
           }
        }
        return null;
    }

    @Override
    public String login(String userAcc, String pwd, boolean isogeny, boolean ifRemember) {
        SsoUser ssoUser = ssoUserDao.queryByUserAccount(userAcc);
        String result = null;
        if (ssoUser != null) {
            Integer userStatus = ssoUser.getUserStatus();
            if (userStatus == 1) {
                if (assertPwd(pwd, ssoUser.getUserPwd())) {
                    ssoUser.setPwdErrorCount(0);
                    ssoUser.setLastLoginTime(new Date());
                    SsoLoginRecord entity = new SsoLoginRecord();
                    if (!isogeny) {
                        String ticket = IdUtil.simpleUUID();
                        entity.setTicket(ticket);
                        Date ticketExpireTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
                        entity.setTicketExpireTime(ticketExpireTime);
                        result = ticket;
                    } else {
                        Date tokenExpireTime = null;
                        Long timeout = null;
                        if (ifRemember) {
                            timeout = (long)(7 * 24 * 60 * 60 * 1000);
                        } else {
                            timeout = (long)(24 * 60 * 60 * 1000);
                        }
                        String token = IdUtil.simpleUUID();
                        tokenExpireTime = new Date(System.currentTimeMillis() + timeout);
                        User user = new User();
                        user.setDeptId(ssoUser.getDeptId());
                        user.setDeptName(ssoDeptDao.queryByDeptId(ssoUser.getDeptId()));
                        user.setMobileNo(ssoUser.getMobileNo());
                        user.setUserAccount(ssoUser.getUserAccount());
                        user.setUserId(ssoUser.getUserId());
                        user.setUserName(ssoUser.getUserName());
                        user.setRoleDtos(roleService.queryUserRoles(ssoUser.getUserId()));
                        redisTemplate.opsForValue().set(token, user, timeout, TimeUnit.MILLISECONDS);
                        entity.setTokenExpireTime(tokenExpireTime);
                        entity.setToken(token);
                        result = token;
                    }
                    entity.setLoginIp(CR.getIp());
                    entity.setLoginTime(new Date());
                    entity.setUserId(ssoUser.getUserId());
                    ssoLoginRecordDao.save(entity);
                    ssoUser.updateById();
                    return result;
                } else {
                    ssoUser.setPwdErrorCount(ssoUser.getPwdErrorCount() + 1);
                    if (ssoUser.getPwdErrorCount() >= config.getMaxLoginFailCount()) {
                        ssoUser.setUserStatus(0);
                    }
                    ssoUser.updateById();
                }
            }
        }
        return null;
    }
    
    private boolean assertPwd(String pwd1, String pwd2) {
        try {
            PrivateKey privateKey = RsaUtil.loadPrivateKey(Constant.privateKey);
            String p1 = new String(RsaUtil.decryptByPrivateKey(Base64Utils.decode(pwd1), privateKey));
            String p2 = new String(RsaUtil.decryptByPrivateKey(Base64Utils.decode(pwd2), privateKey));
            if (p1.equals(p2)) {
                return true;
            }
        } catch (Exception e) {
        }
        return false;
    }
    
    @Override
    public String ticketSwapToken(String ticket) {
        SsoLoginRecord loginRecord = ssoLoginRecordDao.queryByticket(ticket);
        Date ticketExpireTime = loginRecord.getTicketExpireTime();
        if (ticketExpireTime.getTime() < System.currentTimeMillis()) {
            return null;
        }
        if (loginRecord.getToken() == null) {
            Date tokenExpireTime = null;
            Long timeout = (long)(24 * 60 * 60 * 1000);
            String token = IdUtil.simpleUUID();
            tokenExpireTime = new Date(System.currentTimeMillis() + timeout);
            SsoUser ssoUser = ssoUserDao.queryByUserId(loginRecord.getUserId());
            User user = new User();
            user.setDeptId(ssoUser.getDeptId());
            user.setDeptName(ssoDeptDao.queryByDeptId(ssoUser.getDeptId()));
            user.setMobileNo(ssoUser.getMobileNo());
            user.setUserAccount(ssoUser.getUserAccount());
            user.setUserId(ssoUser.getUserId());
            user.setUserName(ssoUser.getUserName());
            user.setRoleDtos(roleService.queryUserRoles(ssoUser.getUserId())); 
            redisTemplate.opsForValue().set(token, user, timeout, TimeUnit.MILLISECONDS);
            loginRecord.setToken(token);
            loginRecord.setTokenExpireTime(tokenExpireTime);
            loginRecord.setLoginTime(new Date());
            loginRecord.updateById();
            return token;
        }
        return null;
    }

    @Override
    public void addUser(AddUserReq user) {
        if (user.getUserPwd().length() < 6) {
            throw new BizException(CodeEnum.F_000001.getCode(), "密码至少6位");
        }
        try {
            this.checkDept(user.getDeptId());
            this.checkMobileNo(user.getMobileNo());
            SsoUser ssoUser = new SsoUser();
            ssoUser.setMobileNo(user.getMobileNo());
            ssoUser.setUserAccount(user.getUserAccount());
            ssoUser.setUserId(IdUtil.simpleUUID());
            ssoUser.setUserName(user.getUserName());
            ssoUser.setUserPwd(Base64Utils.encode(RsaUtil.encryptByPublicKey(user.getUserPwd().getBytes(), RsaUtil.loadPublicKey(Constant.publicKey))));
            ssoUser.setUserStatus(1);
            ssoUser.setDeptId(user.getDeptId());
            ssoUser.insert();
        } catch (Exception e) {
            log.error("error", e);
            throw new BizException(CodeEnum.F_000005);
        }
    }

    @Override
    public String getTicket(User user) {
        SsoLoginRecord entity = new SsoLoginRecord();
        String ticket = IdUtil.simpleUUID();
        entity.setTicket(ticket);
        entity.setUserId(user.getUserId());
        Date ticketExpireTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
        entity.setTicketExpireTime(ticketExpireTime);
        entity.insert();
        return ticket;
    }
    
    @Transactional
    @Override
    public void updatePwd(UpdatePwdReq req) {
        User user = SsoUserHolder.get();
        SsoUser ssoUser = ssoUserDao.queryByUserId(user.getUserId());
        if (!assertPwd(ssoUser.getUserPwd(), req.getOldPwd())) {
            throw new BizException(CodeEnum.F_000008);
        }
        try {
            String newPwd = new String(RsaUtil.decryptByPrivateKey(Base64Utils.decode(req.getNewPwd()), RsaUtil.loadPrivateKey(Constant.privateKey)));
            if (newPwd.length() < 6) {
                throw new BizException(CodeEnum.F_000001.getCode(), "密码至少6位");
            }
            if ("123456".equals(newPwd)) {
                throw new BizException(CodeEnum.F_000001.getCode(), "新密码不能为默认密码");
            }
            ssoUser.setUserPwd(Base64Utils.encode(RsaUtil.encryptByPublicKey(newPwd.getBytes(), RsaUtil.loadPublicKey(Constant.publicKey))));
            ssoUser.updateById();
        } catch (BizException e) {
            throw e;
        } catch (Exception e) {
            throw new BizException(CodeEnum.F_000009);
        }
    }

    @Override
    public void lockUser(LockUserReq req) {
        SsoUser user = ssoUserDao.queryByUserId(req.getUserId());
        if (user == null) {
            throw new BizException(CodeEnum.F_000010);
        }
        user.setUserStatus(0);
        user.updateById();
    }

    @Override
    public void unlockUser(LockUserReq req) {
        SsoUser user = ssoUserDao.queryByUserId(req.getUserId());
        if (user == null) {
            throw new BizException(CodeEnum.F_000010);
        }
        user.setUserStatus(1);
        user.updateById();
    }

    @Override
    public PageResp<User> userPageList(UserPageListReq req) {
        SsoUser query = new SsoUser();
        query.setDeptId(req.getDeptId());
        query.setMobileNo(req.getMobileNo());
        QueryWrapper<SsoUser> queryWrapper = new QueryWrapper<SsoUser>(query);
        if (req.getUserName() != null) {
            queryWrapper.like("user_name", req.getUserName());
        }
        if (req.getUserAccount() != null) {
            queryWrapper.like("user_account", req.getUserAccount());
        }
        queryWrapper.orderByDesc("id");
        IPage<SsoUser> page = new Page<>(req.getPage(), req.getSize());
        IPage<SsoUser> iPage = ssoUserDao.page(page, queryWrapper);
        PageResp<User> pageResp = new PageResp<>();
        List<SsoUser> users = iPage.getRecords();
        List<User> lists = new ArrayList<>();
        if (!CollectionUtils.isEmpty(users)) {
            for (SsoUser ssoUser : users) {
                User user = new User();
                user.setDeptId(ssoUser.getDeptId());
                user.setDeptName(ssoDeptDao.queryByDeptId(ssoUser.getDeptId()));
                user.setRoleDtos(roleService.queryUserRoles(ssoUser.getUserId()));
                user.setMobileNo(ssoUser.getMobileNo());
                user.setUserAccount(ssoUser.getUserAccount());
                user.setUserId(ssoUser.getUserId());
                user.setUserName(ssoUser.getUserName());
                user.setUserStatus(ssoUser.getUserStatus());
                lists.add(user);
            }
        }
        pageResp.setLists(lists);
        pageResp.setTotal(iPage.getTotal());
        return pageResp;
    }

    @Override
    public void updateUser(UpdateUserReq req) {
        SsoUser ssoUser = ssoUserDao.queryByUserId(req.getUserId());
        if (ssoUser == null) {
            throw new BizException(CodeEnum.F_000010);
        }
        if (req.getDeptId() != null) {
            this.checkDept(req.getDeptId());
            ssoUser.setDeptId(req.getDeptId());
        }
        if (req.getMobileNo() != null) {
            if (!req.getMobileNo().equals(ssoUser.getMobileNo())) {
                this.checkMobileNo(req.getMobileNo());
            }
            ssoUser.setMobileNo(req.getMobileNo());
        }
        if (req.getUserName() != null) {
            ssoUser.setUserName(req.getUserName());
        }
        ssoUser.updateById();
    }
    
    private void checkDept(Long deptId) {
        SsoDept dept = ssoDeptDao.getById(deptId);
        if (dept == null) {
            throw new BizException(CodeEnum.F_000010.getCode(),"部门不存在");
        }
    }
    
    private void checkMobileNo(String mobileNo) {
        SsoUser ssoUser = ssoUserDao.queryByMobileNo(mobileNo);
        if (ssoUser != null) {
            throw new BizException(CodeEnum.F_000001.getCode(), "手机号已存在");
        }
    }

    @Override
    public boolean checkApp(Long appId, String appSecret) {
        SsoApp app = ssoAppDao.getById(appId);
        if (app != null) {
            if (app.getAppSecret() != null && app.getAppSecret().equals(appSecret)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void resetPwd(ResetPwdReq req) {
        SsoUser ssoUser = ssoUserDao.queryByUserId(req.getUserId());
        if (ssoUser == null) {
            throw new BizException(CodeEnum.F_000001.getCode(), "用户不存在");
        }
        try {
            ssoUser.setUserPwd(Base64Utils.encode(RsaUtil.encryptByPublicKey("123456".getBytes(), RsaUtil.loadPublicKey(Constant.publicKey))));
            ssoUser.updateById();
        } catch (Exception e) {
            throw new BizException(CodeEnum.F_999999.getCode(),"重置失败");
        }
    }

    @Override
    public boolean isUserInitPwd(String userId) {
        SsoUser ssoUser = ssoUserDao.queryByUserId(userId);
        String pwd = null;
        try {
            pwd = new String(RsaUtil.decryptByPrivateKey(Base64Utils.decode(ssoUser.getUserPwd()), RsaUtil.loadPrivateKey(Constant.privateKey)));
        } catch (Exception e) {
            
        }
        if ("123456".equals(pwd)) {
            return true;
        }
        return false;
    }
}
